var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');


// 引入处理post数据的模块
const bodyParser = require('body-parser')
//引入api 路由接口
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/user');
var activityRouter = require('./routes/activity')

var session = require('express-session');
var mongoStore = require('connect-mongo')(session);
//连接数据库
var dbUrl = 'mongodb://localhost:27017/ydd';
mongoose.connect(dbUrl,(err)=>{
  if(!err){
    console.log('mongodb连接成功');
  }
});

var app = express();

// 引入七牛云配置
const qnconfig = require('./config.js')
// 处理上传七牛云请求
app.get('/token', (req, res, next) => {
  // console.log(qnconfig.uploadToken)
  res.status(200).send(qnconfig.uploadToken)
})
// view engine setup
app.set('views', path.join(__dirname, './app/views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
//登录后将用户信息保存下来，需要使用session中间件，它依赖cookieParser中间件
app.use(session({
  secret:'ydd',
  store: new mongoStore({
    url: dbUrl,
    collection: 'sessions'
  })
}));

app.use(express.static(path.join(__dirname, 'public')));

//api
app.use('/',indexRouter);
app.use('/user', usersRouter);
app.use('/activity',activityRouter);


// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
